from forms.ui_config_database import Ui_Dialog
from PyQt5 import QtWidgets
import pymysql
from PyQt5.QtCore import pyqtSignal

class DialogConfigDatabase(QtWidgets.QDialog, Ui_Dialog):
    # 定义信号
    signal_config_database = pyqtSignal(str, str, str, str, str)  # 发送配置的数据库信息

    def __init__(self, parent=None, host="", port="", user="", password="", database=""):
        super(DialogConfigDatabase, self).__init__(parent)
        self.setupUi(self)

        # 设置初始值
        self.LineEdit.setText(host)
        self.LineEdit_2.setText(port)
        self.LineEdit_3.setText(user)
        self.LineEdit_4.setText(password)
        self.LineEdit_5.setText(database)

        # 将默认的ok与cancel文本修改为确定与取消
        self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText('确定')
        self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setText('取消')

        # 连接信号槽
        self.pushButton.clicked.connect(self.test_connect)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def test_connect(self): 
        # 测试连接数据库
        self.host = self.LineEdit.text()
        self.port = self.LineEdit_2.text()
        self.user = self.LineEdit_3.text()
        self.password = self.LineEdit_4.text()
        self.database = self.LineEdit_5.text()
        try:
            conn = pymysql.connect(host=self.host, port=int(self.port), user=self.user, password=self.password, database=self.database)
            self.label_6.setText('连接成功！')
            self.label_6.setStyleSheet('color: green')
            conn.close()
        except Exception as e:
            print(str(e))
            self.label_6.setText('连接失败！')
            self.label_6.setStyleSheet('color: red')

    def accept(self):
        # 配置数据库
        self.host = self.LineEdit.text()
        self.port = self.LineEdit_2.text()
        self.user = self.LineEdit_3.text()  
        self.password = self.LineEdit_4.text()
        self.database = self.LineEdit_5.text()
        if self.host and self.port and self.user and self.password and self.database:
            print('配置数据库成功！')
            self.signal_config_database.emit(self.host, self.port, self.user, self.password, self.database)
            super().accept()
        else:
            self.label_6.setText('配置不能为空！')
            self.label_6.setStyleSheet('color: red')